const { resolve } = require('path')
const childProcess = require('child_process');
const DACHAGUI_VERSION = childProcess.execSync('git rev-parse HEAD').toString().substr(0, 7);
const { startsWith, replace } = require('lodash/fp');

module.exports = {
    entry: 'src/index.js',
    plugins: [
        ['ice-plugin-fusion', {
            themePackage: '@icedesign/skin',
            themeConfig: {
                // nextPrefix: 'nextfd-',
                theme: 'light',
                primaryColor: '#20A598',
                secondaryColor: '#95A2B2',
            },
        }],
        ['ice-plugin-moment-locales', {
            locales: ['zh-cn'],
        }]
    ],
    externals: {
        'react': 'React',
        'react-dom': 'ReactDOM'
    },
    chainWebpack: config => {
        config.output.path(resolve(process.env.DACHAGUI_FE_BUILD_PATH || 'dist'))
        config.output.publicPath(process.env.DACHAGUI_PUBLIC_PATH || '/')
        config.resolve.alias.set(["~"], resolve(__dirname, "src"))
        config.resolve.modules.add(resolve('./src')).add(resolve('./node_modules'))
        config.plugin('CopyWebpackPlugin').tap(args => [[{ from: 'public/assets', to: 'assets' }]])
        config.plugin('env').use(require.resolve('webpack/lib/EnvironmentPlugin'), [{ ...process.env }])
        config.plugin('HtmlWebpackPlugin').tap(args => [{
            inject: false,
            hash: false,
            template: './public/index.html',
            minify: false,
            templateParameters: (compilation, assets, preparedAssetTags, options) => ({
                NODE_ENV: process.env.NODE_ENV,
                __VERSION__: DACHAGUI_VERSION,
                files: assets
            })
        }])
        config.devServer.before(app => {
            app.use(function (req, res, next) {
                if (startsWith('/web/')(req.url)) {
                    req.url = replace('/web/', '/')(req.url)
                } else if (req.url.split('.').length < 2) {
                    req.url = '/';
                }
                next();
            });
        })
    }
};
